package org.core.tliaswebmanagement.controller;

import lombok.extern.slf4j.Slf4j;
import org.core.tliaswebmanagement.anno.Log;
import org.core.tliaswebmanagement.pojo.Dept;
import org.core.tliaswebmanagement.pojo.Result;
import org.core.tliaswebmanagement.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

//完整请求路径=类上的注解+方法上的注解
@Slf4j
@RequestMapping("/depts")
@RestController
public class DeptController {

    @Autowired
    private DeptService  deptService;

    //@RequestMapping(value = "/depts", method = RequestMethod.GET)
    @GetMapping
    public Result list() {
//        System.out.println("query all");
        log.info("查询所有部门");
        List<Dept> deptList = deptService.findAll();
        return Result.success(deptList);
    }

    //方式一 参数固定为字符串
//    @DeleteMapping("/depts")
//    public Result delete(HttpServletRequest request) {
//        String idStr = request.getParameter("id");
//        int id = Integer.parseInt(idStr);
//        System.out.println("delete " + id);
//        return Result.success();
//    }
    //方式二 @RequestParam("id") Integer id
    //require为true时(不写默认为true)，注意必须携带参数，否则报错
//    @DeleteMapping("/depts")
//    public Result delete(@RequestParam(value = "id", required = true) Integer deptId) {
//        System.out.println("delete " + deptId);
//        return Result.success();
//    }
    //省略@RequestParam(请求参数名与形参名一致)
    @Log
    @DeleteMapping
    public Result delete(Integer id) {
        if(deptService.hasEmp(id))return Result.error("该部门下有员工");
        log.info("根据id删除部门：{} " + id);
        deptService.deleteById(id);
        return Result.success();
    }

    @Log
    @PostMapping
    public Result add(@RequestBody Dept dept) {
//        System.out.println("add " + dept);
        log.info("添加部门：{} " + dept);
        deptService.add(dept);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result getInfo(@PathVariable Integer id) {
//        System.out.println("get " + id);
        log.info("根据id查询部门：{} " + id);
        Dept dept = deptService.getById(id);
        return Result.success(dept);
    }

    @Log
    @PutMapping
    public Result update(@RequestBody Dept dept) {
//        System.out.println("update " + dept);
        log.info("修改部门：{} " + dept);
        deptService.update(dept);
        return Result.success();
    }
}
